package com.mars.service;

import com.google.common.base.Preconditions;
import com.mars.beans.PageQuery;
import com.mars.beans.PageResult;
import com.mars.common.RequestHolder;
import com.mars.dao.SysUserMapper;
import com.mars.exception.ParamException;
import com.mars.param.UserParam;
import com.mars.pojo.SysUser;
import com.mars.util.BeanValidator;
import com.mars.util.IpUtil;
import com.mars.util.MD5Util;
import com.mars.util.PasswordUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author MARS
 * @date 2018/1/7
 */

@Service
public class SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysLogService sysLogService;

    public void save(UserParam userParam){
        BeanValidator.check(userParam);

        if (checkTelephoneExist(userParam.getTelephone(),userParam.getId())) {
            throw new ParamException("电话已被占用");
        }

        if (checkEmailExist(userParam.getMail(),userParam.getId())) {
            throw new ParamException("邮箱已被占用");
        }

        String password = PasswordUtil.randomPassword();
        // TODO :sendEmail
        password = "123456";
        // 加密
        String encryptedPassword = MD5Util.encrypt(password);

        SysUser sysUser = SysUser.builder().username(userParam.getUsername()).telephone(userParam.getTelephone()).mail(userParam.getMail())
                .password(encryptedPassword).deptId(userParam.getDeptId()).status(userParam.getStatus()).remark(userParam.getRemark()).build();
        sysUser.setOperator(RequestHolder.getCurrentUser().getUsername());
        sysUser.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        sysUser.setOperateTime(new Date());

        //TODO 发送email

        sysUserMapper.insertSelective(sysUser);
        // 记录日志
        sysLogService.saveUserLog(null,sysUser);
    }

    /**
     * 校验邮箱是否存在
     * @param mail
     * @param userId
     * @return
     */
    public boolean checkEmailExist(String mail,Integer userId){
        return sysUserMapper.countByMail(mail,userId) > 0;
    }

    /**
     * 校验手机是否存在
     * @param telephone
     * @param userId
     * @return
     */
    public boolean checkTelephoneExist(String telephone,Integer userId){
        return sysUserMapper.countByMail(telephone,userId) > 0 ;
    }

    /**
     * 更新用户信息
     * @param userParam
     */
    public void update(UserParam userParam){
        BeanValidator.check(userParam);
        if (checkTelephoneExist(userParam.getTelephone(),userParam.getId())) {
            throw new ParamException("电话已被占用");
        }
        if (checkEmailExist(userParam.getMail(),userParam.getId())) {
            throw new ParamException("邮箱已被占用");
        }

        // 获取更新之前的用户
        SysUser before = sysUserMapper.selectByPrimaryKey(userParam.getId());
        Preconditions.checkNotNull(before,"待更新的用户不存在");

        // 获取更新之后的用户
        SysUser after = SysUser.builder().id(userParam.getId()).username(userParam.getUsername()).telephone(userParam.getTelephone()).mail(userParam.getMail())
                .deptId(userParam.getDeptId()).status(userParam.getStatus()).remark(userParam.getRemark()).build();
        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        after.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        after.setOperateTime(new Date());

        sysUserMapper.updateByPrimaryKeySelective(after);
        // 记录日志
        sysLogService.saveUserLog(before,after);
    }

    /**
     * 用户名可以通过手机号或者邮箱登陆前的 查找
     * @param keyword
     * @return
     */
    public SysUser findBykeyword(String keyword) {
        return sysUserMapper.findBykeyword(keyword);
    }

    public PageResult<SysUser> getPageByDeptId(int deptId , PageQuery page){
        BeanValidator.check(page);
        int count  =  sysUserMapper.countBydeptId(deptId);

        if (count > 0 ) {
            List<SysUser> list = sysUserMapper.getPageByDeptId(deptId,page);
            return PageResult.<SysUser>builder().total(count).data(list).build();
        }
        return PageResult.<SysUser>builder().build();
    }

    public List<SysUser> getAll(){
        return sysUserMapper.getAll();
    }
}
